package com.fept.msgcore.msgserver.protocol.model.base;

import com.fept.msgcore.msgserver.util.system.ByteUtil;

/**
 * Created by Srma on 1/13/2017.
 */
public class BaseTLVSegment extends BaseSegment {
    /**
     *
     */
    private static final long serialVersionUID = -5423317652272083203L;
    private int type;
    private int length;
    private byte[] value;

    /**
     *
     */
    @Override
    public byte[] pack() {
        byte[] data = new byte[2 + 2 + this.value.length];
        data[0] = (byte) ((this.type >> 8) & 0xFF);
        data[1] = (byte) ((this.type) & 0xFF);
        data[2] = (byte) ((this.length >> 8) & 0xFF);
        data[3] = (byte) ((this.length) & 0xFF);
        System.arraycopy(this.value, 0, data, 4, this.length);
        return data;
    }

    /**
     *
     */
    @Override
    public void unpack(byte[] data, int offset) {
        this.type = ByteUtil.getIntFromBytes(data, offset, 2);
        offset += 2;
        this.length = ByteUtil.getIntFromBytes(data, offset, 2);
        offset += 2;

        this.value = new byte[this.length];
        System.arraycopy(data, offset, this.value, 0, this.length);
    }

    @Override
    final public int getBytesLength() {
        return (2 + 2 + this.value.length);
    }

    /**
     * @return the type
     */
    public int getType() {
        return type;
    }

    /**
     * @param type
     *            the type to set
     */
    public void setType(int type) {
        this.type = type;
    }

    /**
     * @return the length
     */
    public int getLength() {
        return length;
    }

    /**
     * @param length
     *            the length to set
     */
    public void setLength(int length) {
        this.length = length;
    }

    /**
     * @return the value
     */
    public byte[] getValue() {
        return value;
    }

    /**
     * @param value
     *            the value to set
     */
    public void setValue(byte[] value) {
        this.value = value;
    }
}
